package com.sunyard.manage.util;

import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 字段校验工具类
 *
 * @author guangw.dang
 * @Date: 2022/5/11 15:21
 */
public class ValidatorUtils {

    /**
     * 创建validator工厂
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 对实体类进行校验
     *
     * @param obj [obj]
     * @author: guangw.dang
     * @Date: 2022/3/4 9:08
     **/
    public static void beanValidate(@Valid Object obj) throws IllegalArgumentException {

        if (obj instanceof Collection) {
            ValidCollection validCollection = new ValidCollection();
            validCollection.setList((Collection) obj);
            validate(validCollection);
        } else {
            validate(obj);
        }
    }

    /**
     * 参数校验
     *
     * @param obj [obj]
     * @author: guangw.dang
     * @Date: 2022/3/4 9:10
     **/
    public static void validate(@Valid Object obj) {
        List<String> validatedMsg = new ArrayList<>();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
            validatedMsg.add(constraintViolation.getMessage());
        }
        if (!ObjectUtils.isEmpty(constraintViolations)) {
            throw new IllegalArgumentException(validatedMsg.toString());
        }
    }

    /**
     * 参数校验
     *
     * @author: guangw.dang
     * @Date: 2022/3/4 9:11
     **/
    private static class ValidCollection<T> {
        /**
         * 参数为list集合
         */
        @Valid
        private Collection<T> list;

        /**
         * getList
         *
         * @return java.util.Collection
         * @author: guangw.dang
         * @Date: 2022/3/4 9:11
         **/
        public Collection<T> getList() {
            return list;
        }

        /**
         * setList
         *
         * @param list [list]
         * @author: guangw.dang
         * @Date: 2022/3/4 9:12
         **/
        public void setList(Collection<T> list) {
            this.list = list;
        }
    }
}
